package com.swxc.smartorder.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.lzy.okgo.model.HttpParams;
import com.swxc.smartorder.R;
import com.swxc.smartorder.app.ConfigSPS;
import com.swxc.smartorder.app.GlobalAPI;
import com.swxc.smartorder.entity.BackEntity;
import com.swxc.smartorder.network.NetworkHelper;
import com.swxc.smartorder.ui.base.BaseActivity;
import com.swxc.smartorder.utils.AppSharePreferenceMgr;
import com.swxc.smartorder.utils.JsonUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Author   Administrator
 * Date     2018/4/2
 * Desc     eg
 *
 * @author Administrator
 */
public class ForgetPwdActivity extends BaseActivity implements View.OnClickListener {


    private static final long MAX_COUNT_TIME = 60;
    private static final String TAG = "ForgetPwdActivity";
    /**
     * EditText总个数
     */
    private final int EDIT_TEXT_AMOUNT = 6;
    private Observable<Long> mObservableCountTime;
    private Consumer<Long> mConsumerCountTime;
    private Disposable mDisposable;
    private TextView mTvVerification;
    private Button mBtnNext;
    private EditText mEdtPhone;
    private ImageView mIvBack;
    private EditText mEdtVerification;
    /**
     * EditText有内容的个数
     */
    private int mEditTextHaveInputCount = 0;
    /**
     * 编辑框监听器
     */
    private TextWatcher mTextWatcher;
    private NetworkHelper mNetworkHelper;

    String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);
        initViewAndEvent();
        initRxJava();
    }

    private void initViewAndEvent() {
        mNetworkHelper = new NetworkHelper(this, this.getSupportFragmentManager());
        mTvVerification = findViewById(R.id.tv_verification);
        mEdtVerification = findViewById(R.id.edt_verification);
        account = (String) AppSharePreferenceMgr.get(getMContext(), ConfigSPS.USER_ACCOUNT, "");

        mBtnNext = findViewById(R.id.btn_next);
        mEdtPhone = findViewById(R.id.edt_account);
        mIvBack = findViewById(R.id.iv_back);
        mBtnNext.setEnabled(false);
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mEdtPhone.setText(account);
        mTextWatcher = new TextWatcher() {

            /** 改变前*/
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                /** EditText最初内容为空 改变EditText内容时 个数加一*/
                if (TextUtils.isEmpty(charSequence)) {

                    mEditTextHaveInputCount++;
                    /** 判断个数是否到达要求*/
                    if (mEditTextHaveInputCount == EDIT_TEXT_AMOUNT) {
                        mBtnNext.setEnabled(true);
                    }
                }
            }

            /** 内容改变*/
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == EDIT_TEXT_AMOUNT) {
                    mBtnNext.setEnabled(true);
                } else {
                    mBtnNext.setEnabled(false);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }


        };

        mEdtVerification.addTextChangedListener(mTextWatcher);
        mBtnNext.setOnClickListener(this);
    }

    @SuppressLint("CheckResult")
    public void initRxJava() {


        //重置验证码按钮。
        RxView.clicks(mTvVerification).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                if (mDisposable != null && !mDisposable.isDisposed()) {
                    //停止倒计时
                    mDisposable.dispose();
                    //重新订阅
                    mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);
                    //按钮可点击
                    RxView.enabled(mBtnNext).accept(true);
                    RxTextView.text(mTvVerification).accept("发送验证码");
                }
            }
        });


        mObservableCountTime = RxView.clicks(mTvVerification)
                //防止重复点击
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                //判断手机号否为空
                .flatMap(new Function<Object, ObservableSource<Boolean>>() {
                    @Override
                    public ObservableSource<Boolean> apply(Object o) {
                        String phone = mEdtPhone.getText().toString();
                        if (TextUtils.isEmpty(phone)) {
                            Toast.makeText(getMContext(), "电话号码不能为空", Toast.LENGTH_SHORT).show();
                            return Observable.empty();
                        }
                        return Observable.just(true);
                    }
                })
                //将点击事件转换成倒计时事件
                .flatMap(new Function<Object, ObservableSource<Long>>() {
                    @Override
                    public ObservableSource<Long> apply(Object o) throws Exception {
                        //更新发送按钮的状态并初始化显现倒计时文字
                        RxView.enabled(mTvVerification).accept(false);
                        RxTextView.text(mTvVerification).accept("剩余 " + MAX_COUNT_TIME + " 秒");

                        //在实际操作中可以在此发送获取网络的请求,,续1s

                        getVerification();

                        return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
                                .take(MAX_COUNT_TIME)
                                //将递增数字替换成递减的倒计时数字
                                .map(new Function<Long, Long>() {
                                    @Override
                                    public Long apply(Long aLong) {
                                        return MAX_COUNT_TIME - (aLong + 1);
                                    }
                                });
                    }
                })
                //切换到 Android 的主线程。
                .observeOn(AndroidSchedulers.mainThread());

        mConsumerCountTime = new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                //当倒计时为 0 时，还原 btn 按钮
                Log.d(TAG, "Observable thread is : " + Thread.currentThread().getName());
                if (aLong == 0) {
                    RxView.enabled(mTvVerification).accept(true);
                    RxTextView.text(mTvVerification).accept("发送验证码");
                } else {
                    RxTextView.text(mTvVerification).accept("剩余 " + aLong + " 秒");
                }
            }
        };

        //订阅
        mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);


    }

    /**
     * 获取用户验证码
     */
    private void getVerification() {

        HttpParams httpParams = new HttpParams();
        httpParams.put("mobile", mEdtPhone.getText().toString().trim());

        mNetworkHelper.getRequestWithoutToken(GlobalAPI.INSTANCE.getGetVerification(), httpParams, new NetworkHelper.NetWorkHelperBack() {
            @Override
            public void requestSuccess(String json) {
                BackEntity backEntity = JsonUtil.fromJson(json, BackEntity.class);
                if (backEntity == null) {
                    return;
                }
                switch (backEntity.getResponseCode()) {
                    case 1001:
                        break;
                    default:
                        showToastError("发送验证码失败");
                        break;
                }
            }

            @Override
            public void requestFail() {
                showToastError("服务器错误");

            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_next:
                verificationNumber();
                break;
            default:
                break;
        }
    }

    /**
     * 验证输入的验证码是否正确
     */
    private void verificationNumber() {

        HttpParams httpParams = new HttpParams();
        httpParams.put("mobile", mEdtPhone.getText().toString().trim());
        httpParams.put("code", mEdtVerification.getText().toString().trim());


        mNetworkHelper.getRequestWithoutToken(GlobalAPI.INSTANCE.getVerification(), httpParams, new NetworkHelper.NetWorkHelperBack() {
            @Override
            public void requestSuccess(String json) {
                BackEntity backEntity = JsonUtil.fromJson(json, BackEntity.class);
                if (backEntity == null) {
                    return;
                }
                switch (backEntity.getResponseCode()) {
                    case 1001:

                        Bundle bundle = new Bundle();
                        bundle.putString("mobile", mEdtPhone.getText().toString().trim());
                        AppSharePreferenceMgr.put(getMContext(), ConfigSPS.USER_ACCOUNT, mEdtPhone.getText().toString().trim());
                        readyGoThenKill(ValidatePwdActivity.class, bundle);
                        break;
                    default:
                        showToastCommon("输入的验证码有误");
                        break;
                }
            }

            @Override
            public void requestFail() {
                showToastError("服务器错误");

            }
        });


    }
}
